const purchaseListModel = require('../models/purchaseListModel');

const purchaseListController = {
    async getAll(req, res) {
        try {
            const data = await purchaseListModel.getAll();
            res.json({ success: true, data });
        } catch (error) {
            console.error(error);
            res.status(500).json({ success: false, message: '获取采购列表失败' });
        }
    },

    async getById(req, res) {
        try {
            const { id } = req.params;
            const data = await purchaseListModel.getById(id);
            if (!data) return res.status(404).json({ success: false, message: '记录不存在' });
            res.json({ success: true, data });
        } catch (error) {
            console.error(error);
            res.status(500).json({ success: false, message: '获取采购详情失败' });
        }
    },

    async create(req, res) {
        try {
            const result = await purchaseListModel.create(req.body);
            res.json({ success: true, message: '创建成功', id: result.id });
        } catch (error) {
            console.error(error);
            res.status(500).json({ success: false, message: '创建采购记录失败' });
        }
    },

    async update(req, res) {
        try {
            const { id } = req.params;
            const result = await purchaseListModel.update(id, req.body);
            res.json({ success: true, message: '更新成功', result });
        } catch (error) {
            console.error(error);
            res.status(500).json({ success: false, message: '更新失败' });
        }
    },

    async delete(req, res) {
        try {
            const { id } = req.params;
            await purchaseListModel.delete(id);
            res.json({ success: true, message: '删除成功' });
        } catch (error) {
            console.error(error);
            res.status(500).json({ success: false, message: '删除失败' });
        }
    }
};

module.exports = purchaseListController;
